package com.jinzhi.jzapi.certificate.controller;


import com.baomidou.mybatisplus.plugins.Page;
import com.jinzhi.common.annotation.Log;
import com.jinzhi.common.base.BaseController;
import com.jinzhi.common.utils.ApiResult;
import com.jinzhi.common.utils.Result;
import com.jinzhi.jzweb.domain.MsgDO;
import com.jinzhi.jzweb.domain.TrainInfoDO;
import com.jinzhi.jzweb.service.MsgService;
import com.jinzhi.jzweb.service.TrainInfoService;
import com.jinzhi.sys.domain.UserDO;
import com.jinzhi.sys.service.UserService;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.*;

import static com.jinzhi.api.util.TokenTag.TOKEN_TAG;

/**
 * 
 * <pre>
 * 
 * </pre>
 * <small> 2021-01-13 14:27:41 | lance</small>
 */
@Slf4j
@RestController
@RequestMapping("/jzApi/trainInfo")
public class ApiTrainInfoController extends BaseController {
	@Autowired
	private TrainInfoService trainInfoService;
	@Autowired
	private MsgService msgService;
	@Autowired
	private UserService userService;
	@GetMapping()
	String TrainInfo(){
	    return "jzweb/trainInfo/trainInfo";
	}
	
	@ResponseBody
	@GetMapping("/list")
	public Result<Page<TrainInfoDO>> list(TrainInfoDO trainInfoDTO){
		// 查询列表数据
		Page<TrainInfoDO> page = trainInfoService.selectPage(getPage(TrainInfoDO.class),
					trainInfoService.convertToEntityWrapper().orderBy("id", false));
		List list = new ArrayList();
		for (int i = 0; i < page.getRecords().size(); i++) {
				TrainInfoDO obj = (TrainInfoDO) page.getRecords().get(i);
			UserDO userDO = userService.selectById(obj.getExamineUser());
			obj.setExamineUserName(userDO.getUsername());
			list.add(obj);
		}
		page.setRecords(list);
        return Result.ok(page);
	}
	
	@GetMapping("/add")
	String add(){
	    return "jzweb/trainInfo/add";
	}

	@GetMapping("/edit/{id}")
	String edit(@PathVariable("id") Integer id,Model model){
		TrainInfoDO trainInfo = trainInfoService.selectById(id);
		model.addAttribute("trainInfo", trainInfo);
	    return "jzweb/trainInfo/edit";
	}
	
	@Log("添加")
	@ResponseBody
	@Transactional
	@RequiresAuthentication
	@PostMapping("/save")
	@ApiOperation(value = "web端-培训站点申请接口", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
	@ApiImplicitParams({@ApiImplicitParam(name = TOKEN_TAG, value = TOKEN_TAG, paramType = "header")})
	public ApiResult<Object> save(@RequestHeader(value = TOKEN_TAG, required = false) String token, TrainInfoDO trainInfo){
		UserDO user = getClientUser(token);

		Map map1 = new HashMap<>();
		map1.put("createUser",user.getId());
		if(trainInfoService.trainInfoByUser(map1)!=null)
			return ApiResult.fail("您已提交过申请，请勿重复提交！");

		trainInfo.setState(0);
		trainInfo.setType(1);
		Map map=new HashMap<>();
		map.put("name",trainInfo.getEnterpriseName());
		map.put("type","1");
		// 查询判断企业名是否在系统内存在
		Map traMap=trainInfoService.trainInfoList(map);
		if(traMap!=null){
			return ApiResult.fail("企业名称已存在！");
		}
		TrainInfoDO t = trainInfoService.findOneByKv("create_user",user.getId().toString(),"state",0,"type",0);
		if(t==null){
			t=trainInfoService.findOneByKv("create_user",user.getId().toString(),"state",0,"type",3);
		}
		//如果存在草稿则update，如果是新建则insert
		if(t!=null){
			trainInfo.setUpdateTime(new Date());
			trainInfo.setId(t.getId());
			trainInfo.setCreateUser(t.getCreateUser());
			trainInfoService.updateById(trainInfo);
		}else{
			trainInfo.setCreateTime(new Date());
			trainInfo.setCreateUser(user.getId());
			trainInfoService.insert(trainInfo);
		}
		//System.out.println(trainInfo.getCooperationEnterprise());
        return ApiResult.success();
	}

	/**
	 * api小程序端-培训站点申请列表数据接口
	 *
	 * @Description: 培训站点信息列表查询，参数：页码，显示数，站点名称（筛选条件），站点类型（筛选条件）
	 * @Param: [current, number, name, type]
	 * @return: com.jinzhi.common.utils.ApiResult<?>
	 * @Author: kl
	 * @Date: 2020-03-04
	 */
	@GetMapping("/selExaminationPointApiPx")
	@Log("api小程序端-培训站点列表数据接口")
	@ApiOperation(value = "api小程序端-培训站点列表数据接口", httpMethod = "GET", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
	@Transactional
	public ApiResult<?> selExaminationPointApiPx(String current, String number, String name) {
		Map map = new HashMap();
		map.put("name",name);
		Page<Map> page = trainInfoService.selectListPage(Integer.parseInt(current), Integer.parseInt(number), map);
		List list = new ArrayList();
		for (int i = 0; i < page.getRecords().size(); i++) {
			Map obj = (Map) page.getRecords().get(i);
			list.add(obj);
		}
		page.setRecords(list);
		return ApiResult.success(page);
	}


	@Log("保存草稿")
	@ResponseBody
	@PostMapping("/saveDraft")
	@ApiOperation(value = "web端-培训站点申请接口", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
	@ApiImplicitParams({@ApiImplicitParam(name = TOKEN_TAG, value = TOKEN_TAG, paramType = "header")})
	public ApiResult<Object> saveDraft(@RequestHeader(value = TOKEN_TAG, required = false) String token, TrainInfoDO trainInfo){
		UserDO user = getClientUser(token);
		TrainInfoDO t = trainInfoService.findOneByKv("create_user",user.getId().toString(),"state",0,"type",0);
		if(t==null){
			t=trainInfoService.findOneByKv("create_user",user.getId().toString(),"state",0,"type",3);
		}
		Map map1 = new HashMap<>();
		map1.put("createUser",user.getId());
		if(trainInfoService.trainInfoByUser(map1)!=null)
			return ApiResult.fail("您已提交过申请，请勿重复提交！");

		trainInfo.setState(0);
		trainInfo.setType(0);
		trainInfo.setCreateUser(user.getId());
		if(t!=null){
			trainInfo.setUpdateTime(new Date());
			trainInfo.setId(t.getId());
			trainInfo.setCreateUser(t.getCreateUser());
			trainInfoService.updateById(trainInfo);
		}else{
			trainInfo.setCreateTime(new Date());
			trainInfo.setCreateUser(user.getId());
			trainInfoService.insert(trainInfo);
		}
		return ApiResult.success();
	}
	
	@Log("修改")
	@ResponseBody
	@RequestMapping("/update")
	public Result<String>  update( TrainInfoDO trainInfo){
		boolean update = trainInfoService.updateById(trainInfo);
		return update ? Result.ok() : Result.fail();
	}
	
	@Log("删除")
	@PostMapping( "/remove")
	@ResponseBody
	public Result<String>  remove( Integer id){
		trainInfoService.deleteById(id);
        return Result.ok();
	}
	
	@Log("批量删除")
	@PostMapping( "/batchRemove")
	@ResponseBody
	public Result<String>  remove(@RequestParam("ids[]") Integer[] ids){
		trainInfoService.deleteBatchIds(Arrays.asList(ids));
		return Result.ok();
	}


	/**
	 * 培训站点审核
	 * @param ids
	 * @param state  1通过  2不通过
	 * @param remark  描述
	 * @return
	 */
	@Log("审核")
	@PostMapping( "/review")
	@ResponseBody
	public Result<String>  review(@RequestParam("ids[]") Long[] ids,Integer state,String remark) {

		if (state.equals(2) || state.equals(1)) {
			int i = 0;
			for (Long id : ids) {
				String valStr="";
				MsgDO msg = new MsgDO();
				//查询这条数据ID
				TrainInfoDO trainInfoDO= trainInfoService.selectById(id);
				trainInfoDO.setExamineUser(this.getUserId());
				trainInfoDO.setExamineTime(new Date());
				SimpleDateFormat sdf=new SimpleDateFormat();

				if(state.equals(2)){
					trainInfoDO.setType(3);
					trainInfoDO.setExamineRemarks(remark);//未通过，添加备注
					msg.setTitle("培训基地审核未通过！");
					valStr="您申请的培训基地审核未通过，"+"审核人"+this.getUser().getUsername()+"审核时间："+sdf.format(new Date())+"不通过原因"+remark;
				}else{
					trainInfoDO.setType(2);
					trainInfoDO.setExamineRemarks("");//审核通过，清空备注
					msg.setTitle("培训基地审核通过！");
					valStr="您申请的培训基地审核通过！"+"审核人"+this.getUser().getUsername()+"审核时间："+sdf.format(new Date());
				}

				boolean b = trainInfoService.updateById(trainInfoDO);

				if(b){

					msg.setContent(valStr);
					msg.setUserId(trainInfoDO.getCreateUser());
					msg.setCreaterDate(new Date());
//						msg.setEnclosure();
					msg.setType(0);
					msg.setMsgType(0);
					msg.setState(0);
					msg.setCreaterId(this.getUserId());
					msgService.insert(msg);
					i++;
				}
			}

			if (i == ids.length) {
				return Result.build(0,"已成功审核：" + i + "条数据");
			} else {
				return Result.fail("审核状态修改失败！");
			}

		}

		else {
			return Result.fail("审核状态修改失败！");
		}
	}

	@Log("详情")
	@PostMapping( "/info")
	@ResponseBody
	public Result<String>  info(@RequestParam("ids[]") Long[] ids,Integer state,String remark) {
		return null;
	}

	/**
	 * api小程序端-站点列表数据接口
	 *
	 * @Description: 站点信息列表查询，参数：页码，显示数，站点名称（筛选条件），站点类型（筛选条件）
	 * @Param: [current, number, name, type]
	 * @return: com.jinzhi.common.utils.ApiResult<?>
	 * @Author: kl
	 * @Date: 2020-03-04
	 */
	@GetMapping("/selTrainPoint")
	@Log("api小程序端-站点列表数据接口")
	@ApiOperation(value = "api小程序端-站点列表数据接口", httpMethod = "GET", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
	@Transactional
	public ApiResult<?> selTrainPoint(String current, String number, String name, String type) {
		return ApiResult.success();
	}

	}
